package com.dh.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.dh.core.auth.dto.AuthRequest;
import com.dh.core.auth.dto.AuthResponse;
import com.dh.core.auth.dto.BaseTransferEntity;
import com.dh.core.auth.utils.JwtTokenUtil;
import com.dh.core.auth.utils.MD5Util;
import com.dh.core.auth.utils.TokenManagementUtil;
import com.dh.core.auth.validator.IReqValidator;
import com.dh.core.common.enums.BizExceptionEnum;
import com.dh.core.common.exception.BussinessException;

import io.swagger.annotations.ApiOperation;


/**
 * 
* @ClassName: AuthController 
* @Description: 登录接口
* @author dinghao
* @date 2018年12月4日 上午9:38:04 
*
 */
@RestController
public class AuthController {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

//    @Resource(name = "simpleValidator")
    @Autowired
    private IReqValidator reqValidator;

    @ApiOperation("用户登录认证接口")
    @PostMapping(value = "${jwt.auth-path}")
    public ResponseEntity<?> createAuthenticationToken(AuthRequest authRequest) {
        boolean validate = reqValidator.validate(authRequest);

        if (validate) {
            final String randomKey = jwtTokenUtil.getRandomKey();
            final String token = jwtTokenUtil.generateToken(authRequest.getUserName(), randomKey);
            // 登录校验后,将用户名和token保存到系统中
            TokenManagementUtil.addToken(authRequest.getUserName(), token);
            return ResponseEntity.ok(new AuthResponse(token, randomKey));
        } else {
            throw new BussinessException(BizExceptionEnum.AUTH_REQUEST_ERROR);
        }
    }
    
    @ApiOperation("将正常参数加密后得到传输对象加密后的参数")
    @PostMapping(value = "/jwtParamesEncrypt")
    public ResponseEntity<?> jwtParamesEncrypt(String salt,String jsonStr){
    	jsonStr = JSON.toJSONString((Object)JSON.parseObject(jsonStr));
        String md5 = MD5Util.encrypt(jsonStr + salt);
        
        BaseTransferEntity baseTransferEntity = new BaseTransferEntity();
        baseTransferEntity.setObject((Object)JSON.parseObject(jsonStr));
        baseTransferEntity.setSign(md5);
        return ResponseEntity.ok(JSON.toJSON(baseTransferEntity));
    }
    
    @PostMapping("/logout")
    @ApiOperation("/登出")
    public ResponseEntity<?> logout(@RequestParam("username") String username){
    	boolean removeToken = TokenManagementUtil.removeToken(username);
    	if(removeToken) {
    		return ResponseEntity.ok("该用户登出成功!");
    	}
    	return ResponseEntity.ok("该用户登出失败!");
    }
}
